package com.example.mptnet;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.example.mptnet.Interfaces.API;
import com.example.mptnet.Models.Items;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class NewOrder extends Fragment {
    SharedPreferences settings;
    Spinner spinner;
    ArrayList<Items> items = new ArrayList<Items>();
    RelativeLayout image;
    private ArrayList<String> files_path = new ArrayList<>();
    private ArrayList<MultipartBody.Part> files = new ArrayList<>();
    Retrofit retrofit;
    API api;
    EditText title, descript;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_new_order, container, false);
        image = view.findViewById(R.id.images);
        settings = getContext().getApplicationContext().getSharedPreferences("SETTINGS", MODE_PRIVATE);
        spinner = view.findViewById(R.id.spinner);
        title = view.findViewById(R.id.title);
        descript = view.findViewById(R.id.descript);
        retrofit = Builder.request();
        api = retrofit.create(API.class);
        Call<ArrayList<Items>> callItems = api.GetItems();
        callItems.enqueue(new Callback<ArrayList<Items>>() {
            @Override
            public void onResponse(Call<ArrayList<Items>> call, Response<ArrayList<Items>> response) {
                if(response.isSuccessful()){
                    items = response.body();
                    ArrayList<String> list_string = new ArrayList<>();
                    for (int i = 0; i < items.size(); i++) {
                        list_string.add(items.get(i).getTitle());
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,list_string);
                    adapter.setDropDownViewResource(androidx.appcompat.R.layout.support_simple_spinner_dropdown_item);
                    spinner.setAdapter(adapter);
                }
            }

            @Override
            public void onFailure(Call<ArrayList<Items>> call, Throwable t) {

            }
        });
        view.findViewById(R.id.addimage).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(Intent.createChooser(new Intent().setType("image/*").setAction(Intent.ACTION_PICK),"Выберите картиночки"),v.getBottom());
            }
        });
        view.findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(title.getText().equals("") || descript.getText().equals("") || files.size() == 0) {
                    Toast.makeText(getContext(), "Не все поля заполнены", Toast.LENGTH_LONG).show();
                    return;
                }
                else{
                    Call<ResponseBody> response = api.createOrder(files, settings.getString("UID", ""), title.getText().toString(), descript.getText().toString(), spinner.getSelectedItem().toString(),"PUT");
                    response.enqueue(new Callback<ResponseBody>() {
                        @Override
                        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                            if (response.isSuccessful()) {
                                Toast.makeText(getContext(), "Заказ успешно создан, ожидайте исполнителя, который напишет вам в телеграмме", Toast.LENGTH_LONG).show();
                                FragmentTransaction ft = getFragmentManager().beginTransaction();
                                ft.replace(R.id.fragment_container, new MainFragment()).addToBackStack(null);
                                ft.commit();
                            }

                        }

                        @Override
                        public void onFailure(Call<ResponseBody> call, Throwable t) {
                            Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }

            }
        });
        return view;
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            files_path.add(filePath.getPath());
            InputStream inputStream = null;
            try {
                inputStream = getContext().getContentResolver().openInputStream(filePath);
                File outputDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                File outputFile = new File(outputDir, "new_image"+filePath.getPath().substring(filePath.getPath().length()-2)+".jpg");
                OutputStream outputStream = new FileOutputStream(outputFile);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer, 0, length);
                }
                inputStream.close();
                outputStream.close();
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            File file = new File(getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES),"new_image"+filePath.getPath().substring(filePath.getPath().length()-2)+".jpg");
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
            MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
            files.add(body);}
        TextView text = new TextView(getContext());
        for (int i = 0; i < files_path.size(); i++) {
            text.append(files_path.get(i)+'\n');
        }
        image.addView(text);
    }
}